<?php
namespace Operator\Model;

/**
 * 后台首页控制器
 */
class SaleMangerModel extends BaseModel
{

    public function __construct()
    {
        parent::__construct();
    }

    //通过订单审核
    public function aduitPass()
    {
        $m   = M('line_orders');
        $oid = I('order_id');
        if ($m->where(['order_id' => $oid])->getField('order_status') != 1) {
            return ['status' => -1, 'msg' => '订单状态错误'];
        }

        $res = $m
            ->where(['order_id' => I('order_id')])
            ->save(['order_status' => 3, 'verifier_id' => session('operator_user.operator_id'), 'close_time' => time()]);
        if ($res !== false) {
            return ['status' => 1, 'msg' => '修改成功'];
        }

    }

    //拒绝订单审核
    public function aduitRefuse()
    {
        $m   = M('line_orders');
        $oid = I('order_id');
        if ($m->where(['order_id' => $oid])->getField('order_status') != 1) {
            return ['status' => -1, 'msg' => '订单状态错误'];
        }
        $res = $m
            ->where(['order_id' => I('order_id')])
            ->save(['order_status' => -2]);
        //释放余位
        // $re1 = $this->resetSeat($oid);
        if ($res !== false && $re1 !== false) {
            return ['status' => 1, 'msg' => '修改成功'];
        }

    }

    /**
     * 取消订单
     */
    public function cancel()
    {
        $m   = M('line_orders');
        $oid = I('order_id');
        //必须是未支付的订单
        if ($m->where(['order_id' => $oid])->getField('order_status') != -1) {
            return ['status' => -1, 'msg' => '订单状态错误'];
        }

        M()->startTrans();
        //释放余位
        $res = $this->resetSeat($oid);
        if ($m->where(['order_id' => $oid])->save(['order_status' => -6]) !== false && $res) {
            $this->oplog('取消订单' . I('order_id'));
            M()->commit();
            return ['status' => 1, 'msg' => '操作成功'];
        }
        return ['status' => -2, 'msg' => '操作失败'];
    }

    /**
     * 确认支付
     */
    public function confirmPay()
    {
        $m   = M('line_orders as l');
        $oid = I('order_id');
        //必须是未支付的订单
        $status = $m
            ->field('order_status,group_status')
            ->join('__PUBLIC_GROUP__ as g on l.group_id = g.group_id')
            ->where(['order_id' => $oid])
            ->find();
        if ($status['order_status'] != -1 && $status['group_status'] != 0) {
            return ['status' => -1, 'msg' => '订单状态错误'];
        }

        // $this->countCost($oid);
        if ($m->where(['order_id' => $oid])->save(['pay_time' => time(), 'order_status' => 1]) !== false) {
            $this->oplog('确认订单' . I('order_id') . '支付');
            return ['status' => 1, 'msg' => '操作成功'];
        }
        return ['status' => -2, 'msg' => '操作失败'];
    }

    /**
     * 按天的饼状营业额
     */
    public function dayData($oid)
    {
        $where = ['o.order_status' => 3];
        //当天的订单ID
        $allOrder = M('line_orders as o')
            ->field('o.order_id,o.total_money,o.adult_num,o.child_num,o.oldMan_num,l.adult_money,l.child_money,l.oldman_money,l.origin_line_id')
            ->join("__PUBLIC_LINE__ as l on l.line_id=o.line_id")
            ->where(['order_id' => $oid])
            ->select();

        //模型
        $order_unit_detail_DB = M('order_unit_detail');
        //供应商总额:给运营商的线路价格+酒店升级+交通升级+保险+补房差
        $all_order_id  = [];
        $base_cost     = 0; //基础成本
        $room_diff     = 0; //给运营商补房差
        $hotel_money   = 0; //给运营商酒店升级费用
        $insure_money  = 0; //给运营商保险升级费用
        $traffic_money = 0; //给运营商交通升级费用

        $hotel_cost   = 0; //供应商酒店成本
        $insure_cost  = 0; //供应商保险成本
        $traffic_cost = 0; //供应商交通成本
        $scenic_cost  = 0; //供应商景区成本

        $operator_cost     = 0; //运营商线路总成本;
        $order_total_money = 0; //运营商营业额

        foreach ($allOrder as $k => $v) {
            $order_total_money += $v['total_money'];
            $all_order_id[] = $v['order_id'];
            $base_cost += $v['adult_num'] * $v['adult_money'] + $v['child_num'] * $v['child_money'] + $v['oldMan_num'] * $v['oldman_money'];
            //运营商使用到的所有单品总成本
            $operator_cost += $order_unit_detail_DB->where(array('order_id' => $v['order_id'], 'is_compose' => 1))->sum('unit_cost');
            //所有产品
            $unitAll = $order_unit_detail_DB->where(array('order_id' => $v['order_id'], 'is_compose' => 0))->select();
            if (empty($unitAll)) {
                continue;
            }

            foreach ($unitAll as $kk => $vv) {
                //给供应商的补房差
                if ($vv['room_diff']) {
                    $room_diff += $vv['room_diff_cost'];
                }
                //给运营商的 升级费用 类型 1交通,2酒店,3景区,4保险
                if ($vv['is_upgrade'] == 1) {
                    //酒店
                    if ($vv['source_type'] == 2) {
                        $hotel_money += $vv['room_count'] * $vv['upgrade_adult_price'];
                    } else {
                        //交通和保险
                        if ($vv['source_type'] == 4) {
                            $insure_money += $vv['adult_count'] * $vv['upgrade_adult_price'] + $vv['child_count'] * $vv['upgrade_child_price'] + $vv['old_man_count'] * $vv['upgrade_adult_price'];
                        } else if ($vv['source_type'] == 1) {
                            $traffic_money += $vv['adult_count'] * $vv['upgrade_adult_price'] + $vv['child_count'] * $vv['upgrade_child_price'] + $vv['old_man_count'] * $vv['upgrade_adult_price'];
                        }
                    }
                }
            }
        }
        //总金额  运营商成本(供应商提供产品部分)
        $totalMoney = $base_cost + $hotel_money + $insure_money + $traffic_money;
        //运营商总成本=供应商成本+运营商自己拼的产品成本;
        $operator_cost += $totalMoney;
        $res = M('line_orders')->where(['order_id' => $oid])->save(['operator_cost' => $operator_cost]);
        if ($res === false) {
            die(json_encode(['status' => -2, 'msg' => '修改订单成本失败']));
        }
    }

    //释放余位
    public function resetSeat($oid)
    {
        $m_h    = M('day_hotel');
        $m_s    = M('day_seat');
        $m_t    = M('day_traffice');
        $m_g    = M('public_group');
        $detail = M('order_detail')
            ->where(['order_id' => $oid, 'source_type' => ['in', '1,2']])
            ->select();
        $order = M('line_orders')
            ->field('out_time,line_id,total_num,group_id')
            ->where(['order_id' => $oid])
            ->find();

        $out_day = date('Y-m-d', $order['out_time']);
        //把团的已收客数量减少
        $re = $m_g
            ->where(['group_id' => $order['group_id']])
            ->setDec('received_num', $order['total_num']);

        $res = $m_s
            ->where(['day' => $out_day, 'line_id' => $order['line_id']])
            ->setInc('surplus_tourist', $order['total_num']);
        if ($res === false || $re === false) {
            M()->rollback();
            die(json_encode(['status' => -1.1, 'msg' => '释放余位失败']));
        }
        foreach ($detail as $v) {
            if ($v['source_type'] == 1) {
                $res = $m_t
                    ->where(['day' => $v['use_date'], 'traffic_priceId' => $v['source_id']])
                    ->setInc('surplus_seat', $v['adult_count'] + $v['child_count'] + $v['old_man_count']);
            } else {
                $res = $m_h
                    ->where(['day' => $v['use_date'], 'room_priceId' => $v['source_id']])
                    ->setInc('surplus_room', $v['room_count']);
            }
            // echo M()->_sql();echo '<br>';
            if ($res === false) {
                M()->rollback();
                die(json_encode(['status' => -1.2, 'msg' => '释放余位失败']));
            }
        }
        return true;
    }

    /**
     * 更改订单状态为已退款
     * @param  integer $back_money  [退款金额]
     * @param  integer $oid         [订单id]
     * @param  integer $close_money [分销商填入的结算金额]
     * @return [array]               [description]
     */
    public function refuse($back_money = 0, $oid = 0, $close_money = 0)
    {
        $oid    = I('order_id', $oid);
        $m      = M('line_orders as l');
        $status = $m
            ->field('order_status, group_status')
            ->join(' __PUBLIC_GROUP__ as g on l.group_id = g.group_id ')
            ->where(['order_id' => $oid])
            ->find();
        //审核通过的订单才能退款
        if ($status['order_status'] != 3
            && $status['order_status'] != -4
            && $status['group_status'] >= 2) {
            return ['status' => -2, 'msg' => '订单状态错误'];
        }
        $res = $m->where(['order_id' => $oid])->save([
            'order_status' => -3,
            'refund_time'  => time(),
            'back_money'   => I('back_money', $back_money),
            'end_need_pay' => I('close_money', $close_money),
            'is_refund'    => 0,
        ]);
        if ($res !== false) {
            $this->oplog('退款订单' . I('order_id'));
            return ['status' => 1, 'msg' => '退款申请已提交'];
        }
        return ['status' => -1, 'msg' => '操作失败'];
    }

    /**
     * 订单列表
     * @param array   $where
     * @param string  $order_status 订单状态
     */
    public function orderList($where, $order_status)
    {
        //数据总条数
        $count = M('line_orders as lo')
            ->field('count(*), sum(total_money) as sum')
            ->join(" __PUBLIC_TOURISTS__ as t force index(order_id)
                on t.order_id = lo.order_id and lo.order_status in ({$order_status})   and is_contact = 1")
            ->join('__PUBLIC_LINE__ as l on l.line_id = lo.line_id')
            ->join("__LINE_RESELLER_PRICE__ as p on p.line_id = lo.line_id and ((p.reseller_id = lo.manager_id and lo.order_type=rp_type) or rp_type=0)")
            ->where($where)
            ->find();
        $page = new \Think\Page($count['count(*)'], 15);
        $show = $page->show();

        $list = M('line_orders as lo')
            ->field('lo.order_num, l.line_name, l.group_num,
                t.tourists_name, t.tourists_phone, lo.total_num,
                lo.adult_num, lo.child_num, lo.oldMan_num,
                p.adult_price, p.child_price, p.oldman_price,
                l.origin_id, lo.create_time, lo.sales_id,
                lo.order_status, lo.manager_id, lo.order_id,
                total_money,leave_num,order_type,g.group_status,origin_line_id')
            ->join(" __PUBLIC_TOURISTS__ as t force index(order_id)
                on t.order_id = lo.order_id and lo.order_status in ({$order_status})  and is_contact = 1")
            ->join('__PUBLIC_LINE__ as l on l.line_id = lo.line_id')
            ->join("__LINE_RESELLER_PRICE__ as p on p.line_id = lo.line_id and ((p.reseller_id = lo.manager_id and lo.order_type=rp_type) or rp_type=0)")
            ->join('__PUBLIC_GROUP__ as g on lo.group_id = g.group_id')
            ->where($where)
            ->order('lo.order_id desc')
            ->limit($page->firstRow, $page->listRows)
            ->select();
        $this->arrangeData($list);

        $sum = round($count['sum'], 2);
        return ['list' => $list, 'show' => $show, 'total_money' => $sum];
    }

    /**
     * 导出excel
     * @param array   $where
     * @param string  $order_status 订单状态
     */
    public function exportExcels($where, $order_status)
    {
        $reseller_id = session('reseller_user.pid') ? session('reseller_user.pid') : session('reseller_user.reseller_id');
        $list = M('line_orders as lo')
            ->field('lo.order_num, l.line_name, l.group_num,
                t.tourists_name, t.tourists_phone, lo.total_num,
                lo.adult_num, lo.child_num, lo.oldMan_num,
                p.adult_price, p.child_price, p.oldman_price,
                l.origin_id, lo.create_time, lo.sales_id,
                lo.order_status, lo.manager_id, lo.order_id,
                total_money,leave_num,order_type')
            ->join(" __PUBLIC_TOURISTS__ as t force index(order_id)
                on t.order_id = lo.order_id and lo.order_status in ({$order_status})  and is_contact = 1")
            ->join('__PUBLIC_LINE__ as l on l.line_id = lo.line_id')
            ->join("__LINE_RESELLER_PRICE__ as p on p.line_id = lo.line_id and ((p.reseller_id = lo.manager_id and lo.order_type=rp_type) or rp_type=0)")
            ->join('__PUBLIC_GROUP__ as g on lo.group_id = g.group_id')
            ->where($where)
            ->order('lo.order_id desc')
            ->select();
        $this->arrangeData2($list);
        $expCellName = [
            ['order_num', '订单号'],
            ['line_name', '线路名称'],
            ['group_num', '団号'],
            ['tourists_name', '游客姓名'],
            ['tourists_phone', '联系方式'],
            ['book_num', '预定人数'],
            ['single_sale', '销售单价'],
            ['total_money', '订单总额'],
            ['store', '直营门店'],
            ['sales', '销售人'],
            ['set_out', '出发城市'],
            ['create_time', '下单时间'],
            ['reseller', '分销商'],
            ['leave_num', '余位'],
            ['group_status', '团状态'],
            ['status', '状态'],
            'audit' => ['audit', '审核状态'],
            ['manager', '负责人'],
        ];
        $fileName = '订单列表';
        if ($order_status == -6) {
            unset($expCellName['audit']);
            $fileName = '订单回收站';
        }
        D('ExportExcel')->exportExcels($fileName, $expCellName, $list);
    }
    /**
     * 整理数据
     * 将对应的销售人、负责人、城市的id换成中文
     * @param  [array] &$list
     */
    private function arrangeData2(&$list)
    {
        $ms       = D('Staff');
        $reseller = $this->changeIndex($ms->getSomeStaff([]));
        $city     = $this->getCity();
        foreach ($list as $k => $v) {
            $list[$k]['order_num']   = $v['order_num'] . ' ';
            $list[$k]['create_time'] = date('Y-m-d', $v['create_time']);
            $list[$k]['set_out']     = $city[$v['origin_id']];
            $list[$k]['book_num']    = "预约人数：{$list[$k]['total_num']} , 大：{$list[$k]['adult_num']} , 小：{$list[$k]['child_num']} ";
            $list[$k]['single_sale'] = " 大：{$list[$k]['adult_price']} , 小：{$list[$k]['child_price']}";
            $list[$k]['manager']     = $reseller[$v['manager_id']]['reseller_name'];
            $list[$k]['sales']       = $reseller[$v['sales_id']]['reseller_name'];
            $list[$k]['line_name']   .=  ($v['origin_line_id'] ? '' : '(自营)') ;
            if ($v['order_type'] == 1) {
                $list[$k]['store']    = $reseller[$v['manager_id']]['reseller_name'];
                $list[$k]['reseller'] = '无';
            } else {
                $list[$k]['reseller'] = $reseller[$v['manager_id']]['reseller_name'];
                $list[$k]['store']    = '无';
            }

            //订单状态处理
            switch ($v['order_status']) {
                case -1:
                    $list[$k]['status'] = '待确认(未支付)';
                    $list[$k]['audit']  = '未审核';
                    break;

                case 1:
                    $list[$k]['status'] = '已支付';
                    $list[$k]['audit']  = '待审核';
                    break;

                case 3:
                    $list[$k]['status'] = '已支付';
                    $list[$k]['audit']  = '已审核';
                    break;

                //订单回收站
                case -6:
                    $list[$k]['status'] = '已取消';
                    $list[$k]['audit']  = '';
                    break;

                case -4:
                    $list[$k]['status'] = '拒绝退款';
                    $list[$k]['audit']  = '已审核';
                    break;

                case -5:
                    $list[$k]['status'] = '已退款';
                    $list[$k]['audit']  = '已审核';
                    break;

            }

            switch ($v['group_status']) {
                case -1:
                    $list[$k]['group_status'] = '不成团';
                    break;
                case 0:
                    $list[$k]['group_status'] = '待出团';
                    break;
                case 1:
                    $list[$k]['group_status'] = '已成团';
                    break;
                case 2:
                    $list[$k]['group_status'] = '已出团';
                    break;
                case 3:
                    $list[$k]['group_status'] = '已回团';
                    break;
            }
        }
    }

    /**
     * 整理数据
     * 将对应的销售人、负责人、城市的id换成中文
     * @param  [array] &$list
     */
    private function arrangeData(&$list)
    {
        $ms       = D('Staff');
        $reseller = $this->changeIndex($ms->getSomeStaff([]));
        $city     = $this->getCity();
        foreach ($list as $k => $v) {
            $list[$k]['create_time'] = date('Y-m-d H:i:s', $v['create_time']);
            $list[$k]['set_out']     = $city[$v['origin_id']];
            $list[$k]['manager']     = $reseller[$v['manager_id']]['reseller_name'];
            $list[$k]['line_name']   .=  ($v['origin_line_id'] ? '' : '(自营)') ;
            $list[$k]['sales']       = $reseller[$v['sales_id']]['reseller_name'];
            if ($v['order_type'] == 1) {
                $list[$k]['store']    = $reseller[$v['manager_id']]['reseller_name'];
                $list[$k]['reseller'] = '无';
            } else {
                $list[$k]['reseller'] = $reseller[$v['manager_id']]['reseller_name'];
                $list[$k]['store']    = '无';
            }
            //订单状态处理
            $list[$k]['html'] = $this->orderStatus($v['order_status'], $v['order_id']);
            switch ($v['group_status']) {
                case -1:
                    $list[$k]['group_text'] = '不成团';
                    break;
                case 0:
                    $list[$k]['group_text'] = '待出团';
                    break;
                case 1:
                    $list[$k]['group_text'] = '已成团';
                    break;
                case 2:
                    $list[$k]['group_text'] = '已出团';
                    break;
                case 3:
                    $list[$k]['group_text'] = '已回团';
                    break;
            }
        }

    }

    /**
     * 订单状态处理
     * @param int $order_status 订单状态
     * @param int $order_id 订单id
     * @return string  $html 页面展示内容
     */
    private function orderStatus($order_status, $order_id)
    {
        switch ($order_status) {
            case -1:
                $html = "<td><button class='btn-primary btn' onclick='confirmPay({$order_id})'>待确认<br/>(未支付)</button></td><td>未审核</td>";
                break;

            case 1:
                $html = "<td>已支付</td><td>待审核</td>";
                break;

            case 3:
                $html = "<td>已支付</td><td>已审核</td>";
                break;
            case -4:
                $html = '<td>拒绝退款</td><td>已审核</td>';
                break;
            case -6:
                $html = '已取消';
                break;
        }
        return $html;
    }

    /**
     * 返回城市信息
     * @return [array] $city [可用的城市信息]
     */
    private function getCity()
    {

        $key = md5('getCity');
        if (!S($key)) {
            $city = M('areas')
                ->field('areaId,areaName')
                ->where([
                    'isShow'   => 1,
                    'areaFlag' => 1,
                    'areaType' => 1,
                ])
                ->select();
            $area_id   = array_map('array_shift', $city);
            $area_name = $this->array_cloumn($city, 'areaName');
            $city      = array_combine($area_id, $area_name);

            S($key, $city, 864000);
        }
        return S($key);
    }

}
